<template>
  <div>
    <div class="search header-card">
        <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="部门">
          <depart-tree
            style="width: 200px"
            class="depart-tree"
            v-model="queryParams.deptNo"
            :departments="departments"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="queryParams.name" size="small"/>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <div style="display: flex;">
        <div v-if="checkAuthority('/teacher/eyes')" class="switch-btn cursor iconfont" :class="[isShow ? 'icon-yanjing': 'icon-biyan']" @click="handleClickIsShow"></div>
        <div>
          <el-button v-if="checkAuthority('/teacher/down')" size="small" type="primary" @click="handleExport">导出教职工码</el-button>
        </div>
        <!-- <el-button size="small" type="primary" @click="handleAdd">添加</el-button>
        <el-button size="small" type="primary" @click="handleBrachAdd">批量添加</el-button> -->
      </div>
      </div>
      <acc-table :tableData="tableData" :columnDefs="columnDefs">
        <template #order={index}>
          <span>{{index | orderIndex(pageVo)}}</span>
        </template>
        <template #idCard={row}>
          <div>{{isShow && row.idCard.length === 18 ?  $options.filters.idCarDesensitization(row.idCard) : row.idCard}}</div>
        </template>
        <template #contact={row}>
          {{isShow ? $options.filters.cellularPhone(row.contact) : row.contact}}
        </template>
        <template #cohabit={row}>
          <div style="width: 90%; overflow:hidden; white-space:nowrap; text-overflow:ellipsis;">
            <el-popover
            placement="bottom"
            width="300"
            trigger="hover">
            <div class="family-member">
              <div class="member mb-10" v-for="(item,index) in row.togetherList" :key="index">
                <div><label>姓名：</label>{{item.name}}</div>
                <div><label>证件号码：</label>{{isShow && item.idNumber.length === 18 ?  $options.filters.idCarDesensitization(item.idNumber) : item.idNumber}}</div>
                <div v-if="item.relation !== null"><label>关系：</label>{{item.relation || '-'}}</div>
              </div>
            </div>
            <span slot="reference"><span class="mr-10 cursor" v-for="(item,index) in row.togetherList" :key="index">{{item.name}}</span></span>
          </el-popover>
          </div>
        </template>
        <template #teachingCode={row}>
          <el-popover placement="bottom" width="230" trigger="hover">
            <el-image
            v-if="tableData.length"
            fit='fill'
            style="width: 200px; height: 200px"
            :src="`/gateway/api/basic/minio/getFileSource?fileName=${row.no}-${row.number}.png&t=${random()}`"
            />
            <span slot="reference" class="cursor">查看</span>
          </el-popover>
        </template>
        <template #action={row}>
          <el-button v-if="checkAuthority('/teacher/select')" size="mini" type="text" @click="handleLook(row)">查看</el-button>
          <el-button v-if="checkAuthority('/teacher/editor')" size="mini" type="text" @click="handleEdit(row)">编辑</el-button>
          <!-- <el-button size="mini" type="text" @click="handleDel(row)">删除</el-button> -->
        </template>
      </acc-table>
      <acc-page :total='total' :page-size='pageVo.pageSize' :current-page='pageVo.pageNum'  @current-change='handleChangePage' @size-change='handleChangeSize'></acc-page>
      <!-- <el-dialog
      :visible.sync="centerDialogVisible"
      width="400px"
      center>
      <AccNew v-if="centerDialogVisible" :dialogData='dialogData' @cancel='handleCancel'></AccNew>
    </el-dialog>
      <el-dialog
      :visible.sync="visibleLook"
      width="50%"
      center>
      <StudentInfo v-if="visibleLook" :dialogData='currentRow' @cancel='handleCancelInfo'></StudentInfo>
    </el-dialog> -->
    <el-dialog
      :visible.sync="visibleBrachAdd"
      width="400px"
      center>
      <div class="import-template" v-if="visibleBrachAdd">
        <div>
          <label>下载模板：</label>
          <el-link type="primary" @click="handleDownload">下载</el-link>
        </div>
        <div class="mb-20">
          <label>导入模板：</label>
          <el-upload
            style="display: inline"
            action=""
            :limit="1"
            :auto-upload='false'
            :show-file-list="true"
            accept=".xls,.xlsx,.zip"
            :before-upload="beforeUpload"
            :on-exceed="onExceed"
            :on-change="fileChange"
            >
            <el-link type="primary">导入</el-link>
          </el-upload>
        </div>
        <div style="text-align: center">
          <el-button size="small" type="primary" @click="handleSave">确定</el-button>
          <el-button size="small" @click="handleCancelAdd">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <teachInfoForm
    :teachForm="teachForm"
    :data="lookTeachFormData"
    @closeteachForm="teachForm.flag = false"
    showAll/>
    <addTeachInfo
    :infoData="infoData"
    :deptData="departments"
    :addTeachForm="addTeachForm"
    :data="addTeachFormData"
    v-if="addTeachForm.flag"
    @closeaddTeachForm="addTeachForm.flag = false"/>
  </div>
</template>

<script>
import { columnDefs } from './mock'
import { getTeacherInfo, getHealthInfoByNo, exportTeacherZip } from '@/views/children/antiepidemic/js/base'
import teachInfoForm from '@/views/children/basic/components/teachInfoForm'
import addTeachInfo from '@/views/children/basic/components/addTeachInfo'
import { sepDataDicInfoQuery } from '@/views/children/basic/js/controllerInfo'
// import AccNew from './New.vue'
// import StudentInfo from './StudentInfo.vue'
import { downloadTemplate, batchImport, queryDeptListBySchoolNo, deleteTeach } from '@/views/children/basic/js/teacherInfo'
import DepartTree from '@/views/children/basic/components/departTree'
import { decrypt } from '@/utils/crypto'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限
export default {
  components: { DepartTree, teachInfoForm, addTeachInfo },
  provide () {
    return {
      handleSearch: () => {
        this.handleSearch()
      }
    }
  },
  data () {
    return {
      isShow: true,
      departments: [],
      infoData: {},
      visibleBrachAdd: false,
      centerDialogVisible: false,
      dialogData: {
        type: 'add',
        id: null
      },
      // 查看
      teachForm: {
        flag: false,
        title: ''
      },
      lookTeachFormData: {},
      addTeachFormData: {},
      // 新增
      addTeachForm: {
        flag: false,
        title: ''
      },
      queryParams: {},
      columnDefs: [],
      tableData: [],
      pageVo: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      // visibleLook: false,
      currentRow: {},
      file: ''
    }
  },
  props: {
    schoolDistrictNo: {
      type: String,
      default: ''
    }
  },
  watch: {
    schoolDistrictNo: {
      handler () {
        this.handleSearch()
      },
      immediate: true
    }
  },
  created () {
    this.columnDefs = columnDefs
    this.queryDeptListBySchoolNo()
    this.sepDataDicInfoQuery()
  },
  methods: {
    checkAuthority,
    random () {
      return Math.random()
    },
    handleClickIsShow () {
      this.isShow = !this.isShow
    },
    queryDeptListBySchoolNo () {
      queryDeptListBySchoolNo({}).then(res => {
        if (res.code === 0) {
          this.departments = res.data
        }
      })
    },
    handleExport () {
      let userInfo = localStorage.getItem('Standard__User-Info')
      let tenantNo = JSON.parse(userInfo).value.tenantNo
      exportTeacherZip({
        schoolDistrictNo: this.schoolDistrictNo,
        tenantNo,
        ...this.queryParams,
        pageSize: 99999,
        pageNum: 1
      }).then(() => {
        this.$message.success('导出成功')
      })
    },
    handleSearch () {
      this.pageVo.pageNum = 1
      this.loadDataList()
    },
    async sepDataDicInfoQuery () {
      const data = await sepDataDicInfoQuery()
      if (data) {
        this.infoData = data.data
        this.postTypes = data.data
      }
    },
    loadDataList () {
      getTeacherInfo({
        ...this.queryParams,
        ...this.pageVo,
        schoolDistrictNo: this.schoolDistrictNo,
        isQueryRoomPeople: 1
      }).then(res => {
        res.data = JSON.parse(decrypt(res.data))
        const { code, data } = res
        if (code === 0) {
          this.total = data.total
          this.tableData = data.records
        }
      })
    },
    handleChangePage (page) {
      this.pageVo.pageNum = page
      this.loadDataList()
    },
    handleChangeSize (size) {
      this.pageVo.pageSize = size
      this.handleSearch()
    },
    handleAdd () {
      // this.dialogData.type = 'add'
      // this.centerDialogVisible = true
      this.addTeachForm.flag = true
      this.addTeachForm.title = '新增教职工信息'
      this.addTeachFormData = {
        isCreateAccount: 1,
        gender: 0,
        cardType: '1',
        nationality: '156',
        positionType: '0'
      }
    },
    handleCancel () {
      this.centerDialogVisible = false
    },
    handleBrachAdd () {
      this.visibleBrachAdd = true
    },
    async handleLook (row) {
      const { code, data } = await getHealthInfoByNo({
        idCard: row.idCard,
        no: row.no
      })
      let healthRecords = []
      let vaccinesJson = {
        1: '已接种一针疫苗',
        2: '已接种两针疫苗',
        3: '已接种三针疫苗'
      }
      if (code === 0 && data && data.length > 0) {
        healthRecords = data.map((item) => {
          let healthRecordsTextArr = [item.antigen, item.healthCode, item.nucleicAcid, item.vaccines ? vaccinesJson[item.vaccines] : '']
          return {
            dateTime: item.dateTime,
            text: healthRecordsTextArr.filter(item => item).join('/')
          }
        })
      }
      this.teachForm.flag = true
      this.teachForm.title = row.title
      this.lookTeachFormData = {
        ...row,
        healthRecords
      }
    },
    handleCancelInfo () {
      this.visibleLook = false
    },
    handleEdit (data) {
      this.addTeachForm.flag = true
      this.addTeachForm.title = '编辑教职工信息'
      this.addTeachFormData = Object.assign(data, {
        nativePlace: this.setRegionTextToCode(data.nativePlace),
        birthPlace: this.setRegionTextToCode(data.birthPlace),
        residenceLocation: this.setRegionTextToCode(data.residenceLocation)
      })
    },
    setRegionTextToCode (region) {
      if (region) {
        return region.split(',')
      }
    },
    handleDel (row) {
      this.$confirm('此操作将删除该教职工信息 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteTeach(row.id)
        this.$message.success('删除成功')
        this.handleSearch()
      }).catch(() => {})
    },
    beforeUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const zipType = file.name.split('.')[1] === 'zip'
      const isLt2M = file.size / 1024 / 1024 < 200
      if (!extension && !extension2 && !zipType) {
        this.$message.warning('导入模板只能是xls、xlsx、zip格式!')
        return false
      } else if (!isLt2M) {
        this.$message.warning('导入模板大小不能超过 200MB!')
        return false
      } else {
        this.loading = this.$loading({
          lock: true,
          text: '正在导入',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        })
        return true
      }
    },
    fileChange (file) {
      this.file = file.raw
    },
    onExceed (files, fileList) {
      this.$message.warning(`只能选择一个文件`)
    },
    async handleSave () {
      try {
        const formData = new FormData()
        formData.append('file', this.file)
        const res = await batchImport(formData)
        if (res.code === 0) {
          this.$message.success('导入成功！')
          this.handleSearch()
        }
      } catch (e) {}
    },
    handleDownload () {
      downloadTemplate()
    },
    handleCancelAdd () {
      this.visibleBrachAdd = false
    }
  }
}
</script>

<style lang='scss' scoped>
.switch-btn{
  width: 50px;
  height: 30px;
  line-height: 30px;
  font-size: 30px;
  text-align: center;
}
.search {
  display: flex;
  justify-content: space-between;
}
.family-member {
  max-height: 150px;
  overflow: hidden;
  overflow-y: auto;
  // .member {
  //   label {
  //     display: inline-block;
  //     width: 70px;
  //   }
  // }
}
.import-template {
  font-size: 18px;
  // display: flex;
  // flex-direction: column;
  // justify-content: center;
  // align-items: center;
  margin-left: 40px;
  label {
    margin-right: 30px;
  }
}
</style>
